package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupSelectFinancial;
import com.cj.mobile.iabp.app.dialog.PopupTipsDialog;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.di.component.DaggerPatientStatisticsComponent;
import com.cj.mobile.iabp.mvp.contract.PatientStatisticsContract;
import com.cj.mobile.iabp.mvp.model.entity.DeptInfo;
import com.cj.mobile.iabp.mvp.model.entity.PatientInfo;
import com.cj.mobile.iabp.mvp.presenter.PatientStatisticsPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.PatientInfoAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2025/09/02 14:47
 * 患者统计
 *
 * @author Love_xie
 * module name is PatientStatisticsActivity
 */
public class PatientStatisticsActivity extends BaseActivity<PatientStatisticsPresenter> implements PatientStatisticsContract.View, DefaultAdapter.OnRecyclerViewItemClickListener {
    /*--------------------------------控件信息--------------------------------*/

    @BindView(R.id.txvi_patientstatistics_start)
    TextView txviStart;
    @BindView(R.id.imvi_patientstatistics_start)
    ImageView imviStart;

    @BindView(R.id.txvi_patientstatistics_end)
    TextView txviEnd;
    @BindView(R.id.imvi_patientstatistics_end)
    ImageView imviEnd;

    @BindView(R.id.txvi_patientstatistics_campus)
    TextView txviCampus;

    @BindView(R.id.txvi_patientstatistics_department)
    TextView txviDepartment;

    @BindView(R.id.txvi_patientstatistics_state)
    TextView txviState;

    @BindView(R.id.revi_patientstatistics_content)
    RecyclerView mRecyclerView;

    @BindView(R.id.lila_patientstatistics_notdata)
    LinearLayout notData;

    @BindView(R.id.linla_patientstatistics_loading)
    View loading;                                                                                   // 加载效果


    /*--------------------------------业务信息--------------------------------*/

    // 状态 弹框
    private PopupSelectFinancial mPopupState;
    // 院区 弹框
    private PopupSelectFinancial mPopupCampus;
    // 科室 弹框
    private PopupSelectFinancial mPopupDepartment;

    // 院区id
    private String mDeptSec;
    // 科室id
    private String mDeptId;
    // 状态
    private String mStateId;

    // 选定的日期
    private Date selectData, endData;

    @Inject
    RecyclerView.LayoutManager mLayoutManager;

    @Inject
    PatientInfoAdapter mAdapter;

    /**
     * 对话框
     */
    private MaterialDialog mDialog;

    @Override
    public void onDestroy() {
        // super.onDestroy()之后会unbind,所有view被置为null,所以必须在之前调用
        DefaultAdapter.releaseAllHolder(mRecyclerView);
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();
        this.mDialog = null;

        this.mLayoutManager = null;
        this.mAdapter = null;
        this.selectData = null;
        this.endData = null;
        this.mPopupState = null;
        this.mPopupCampus = null;
        this.mPopupDepartment = null;
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        flushedData();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerPatientStatisticsComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_patient_statistics;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle("患者统计");
        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).cancelable(false).build();

        loadState();
        selectData = new Date();
        endData = new Date();
        // 初始化RecyclerView
        initRecyclerView();
        if (mPresenter != null)
            mPresenter.initData();
    }

    public void flushedData() {
        if (mPresenter != null)
            mPresenter.getPatientStatistics(false, txviStart.getText().toString(), txviEnd.getText().toString(), mDeptId, mDeptSec, mStateId);
    }

    /**
     * 状态
     */
    public void loadState() {
        List<String> mShow = new ArrayList<>();
        mShow.add("全部");
        mShow.add("现运行");
        mShow.add("撤机关注");
        mShow.add("撤机未关注");
        mShow.add("归档");

        PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
            if (name.equals("全部")) {
                mStateId = "";
            } else if (name.equals("现运行")) {
                mStateId = "0";
            } else if (name.equals("撤机关注")) {
                mStateId = "1";
            } else if (name.equals("撤机未关注")) {
                mStateId = "2";
            } else {
                mStateId = "3";
            }
            txviState.setText(name);
            flushedData();
        };
        mPopupState = new PopupSelectFinancial(this, "状态", mShow, itemClick);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    @OnClick({
            R.id.lila_patientstatistics_start,                                                      // 开始日期
            R.id.imvi_patientstatistics_start,
            R.id.lila_patientstatistics_end,                                                        // 结束日期
            R.id.lila_patientstatistics_campus,                                                     // 选择院区
            R.id.lila_patientstatistics_department,                                                 // 选择科室
            R.id.lila_patientstatistics_state,                                                      // 状态
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lila_patientstatistics_start:                                                 // 开始日期
                onSelectDate(true);
                break;
            case R.id.imvi_patientstatistics_start:
                txviStart.setText("");
                imviStart.setVisibility(View.GONE);
                flushedData();
                break;
            case R.id.lila_patientstatistics_end:                                                   // 结束日期
                onSelectDate(false);
                break;
            case R.id.imvi_patientstatistics_end:
                txviEnd.setText("");
                imviEnd.setVisibility(View.GONE);
                flushedData();
                break;
            case R.id.lila_patientstatistics_campus:                                                // 选择院区
                if (mPopupCampus != null) {
                    mPopupCampus.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    showMessage("暂无院区数据，请联系管理员！");
                }
                break;
            case R.id.lila_patientstatistics_department:                                            // 选择科室
                if (mPopupDepartment != null) {
                    mPopupDepartment.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    showMessage("暂无科室数据，请联系管理员！");
                }
                break;
            case R.id.lila_patientstatistics_state:                                                 // 状态
                if (mPopupState != null) {
                    mPopupState.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
                break;
        }
    }


    /**
     * 加载院区
     */
    @Override
    public void loadCampus(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();
            mShow.add("全部");
            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                if (position == 0) {
                    this.txviCampus.setText(name);
                    this.mDeptSec = "";
                } else {
                    DeptInfo info = mList.get(position - 1);
                    this.txviCampus.setText(CommonUtils.isEmptyReturnStr(info.getName()));
                    this.mDeptSec = String.valueOf(info.getId());

                    this.txviDepartment.setText("全部");
                    this.mDeptId = "";
                    if (mPresenter != null) {
                        mPresenter.getDepartmentList(mDeptSec);
                    }
                }

                flushedData();
            };
            mPopupCampus = new PopupSelectFinancial(this, "院区", mShow, itemClick);
        }
    }

    /**
     * 加载科室
     */
    @Override
    public void loadDepartment(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();
            mShow.add("全部");
            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                if (position == 0) {
                    this.txviDepartment.setText(name);
                    this.mDeptId = "";
                } else {
                    DeptInfo info = mList.get(position - 1);
                    this.txviDepartment.setText(CommonUtils.isEmptyReturnStr(info.getName()));
                    this.mDeptId = String.valueOf(info.getId());
                }

                flushedData();
            };
            mPopupDepartment = new PopupSelectFinancial(this, "科室", mShow, itemClick);
        }
    }

    /**
     * 选择日期
     */
    private void onSelectDate(boolean start) {
        // 起始日期
        Calendar startDate = Calendar.getInstance();
        if (start) {
            // 设置年份
            startDate.set(Calendar.YEAR, 1900);
        } else {
            startDate.setTime(selectData);
        }

        // 终止日期(今天+100年)
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 100);

        TimePickerView pvOptions = new TimePickerView.Builder(this, (date, v) -> {
            if (start) {
                this.selectData = date;
                // yyyy-MM-dd HH:mm:ss
                txviStart.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
                imviStart.setVisibility(View.VISIBLE);
            } else {
                this.endData = date;
                txviEnd.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
                imviEnd.setVisibility(View.VISIBLE);
            }

            flushedData();
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(20)//确定和取消文字大小
                .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimary))//取消按钮文字颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
//                .setCyclic(true, true, true)//循环与否
                .setType(new boolean[]{true, true, true, false, false, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setRangDate(startDate, endDate)
                .build();

        // 设置数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start ? selectData : endData);
        pvOptions.setDate(calendar);
        pvOptions.show();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        notData.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        loading.setVisibility(View.GONE);
    }

    /**
     * 提交时显示loading框
     */
    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    /**
     * 提交后隐藏loading框
     */
    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onItemClick(@NonNull View view, int viewType, @NonNull Object data, int position) {
        if (view.getId() == R.id.tv_opt_select) {
            // 查看
            PatientInfo info = (PatientInfo) data;

            Bundle mBundle = new Bundle();
            mBundle.putString("id", info.getId());
            ActivityUtils.startActivity(mBundle, PatientInfoActivity.class);
        } else if (view.getId() == R.id.tv_opt_del) {
            // 删除
            PatientInfo info = (PatientInfo) data;
            PopupTipsDialog dialog = new PopupTipsDialog(this, "是否删除【" + info.getName() + "】患者信息？", click -> {
                if (click) {
                    if (mPresenter != null) {
                        mPresenter.removePatient(info.getId());
                    }
                }
            });
            dialog.showAtLocation(view, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
        }

    }

    @Override
    public void isNotInfo(boolean isValue) {
        notData.setVisibility(isValue ? View.VISIBLE : View.GONE);
    }
}